package com.thread.sync.sync01;

/**
 * 脏读
 */
public class DirtyRead {
    private String username = "houzheng";
    private String password = "799827577";

    public synchronized void setValue() {
        try {
            this.username = "侯征";
            Thread.sleep(2000);
            this.password = "houzheng";
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("setValue成功: username=" + username + ",password=" + password);
    }

    //考虑业务的整体性,应该在setValue与getValue方法同时加上synchronized,保证业务数据一致性,否则会出现脏读
    public synchronized void getValue() {
        System.out.println("getValue成功: username=" + username + ",password=" + password);
    }

    public static void main(String[] args) {
        DirtyRead dirtyRead = new DirtyRead();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                dirtyRead.setValue();
            }
        });
        t1.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        dirtyRead.getValue();
    }


}
